//
//  YYLComposeView.swift
//  XinlangWeibo
//
//  Created by yangyinglei on 2017/4/4.
//  Copyright © 2017年 yangyinglei. All rights reserved.
//

import UIKit
import pop

class YYLComposeView: UIView {
    
    //按钮的数组
    fileprivate lazy var buttonArray:[YYLComposeButton] = [YYLComposeButton]()
    //按钮的数据
    lazy var btnDataArray: [YYLComposeModel] = {
    
        return self.getPlistData()
    }()
    //获取目标控制器
    var target: UIViewController?
    //MARK:---------------------------------------------------------------------------
    // 自定义罩层
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    fileprivate func setupUI() {

    size = CGSize(width: ScreenWidth, height: ScreenHeight)
        let image = getScreenShot()
        //模糊图片
        let imageView:UIImageView = UIImageView(image: image)
        //图片上的文字
        let slogenView:UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
        //添加按钮
        
        addSubview(imageView)
        imageView.addSubview(slogenView)
        addChildBtn()
        popAnimation(isUp: true)
        
        imageView.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        slogenView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self.snp.top).offset(100)
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        popAnimation(isUp: false)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.45) {
            self.removeFromSuperview()
        }
        
    }
    
    //截屏操作
    fileprivate func getScreenShot() -> UIImage {
    
        let window = UIApplication.shared.keyWindow!
    //开启图片上下文
        UIGraphicsBeginImageContext(window.size)
    //截屏
        window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
    //获取图片
        let currentImage = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭图形上下文
        UIGraphicsEndImageContext()

        return currentImage!.applyLightEffect()
    }
    // 添加按钮的方法
    fileprivate func addChildBtn() {
        let buttonWidth:CGFloat = 80
        let buttonMargin = (ScreenWidth - 3 * buttonWidth) / 4
        let buttonHeight:CGFloat = 110
        
        for i in 0..<6 {
            
            let btn = YYLComposeButton()
            btn.tag = i
            //btn添加点击事件
            btn .addTarget(self, action: #selector(composeBtnClick (btn:)), for: .touchUpInside)
            
            btn.setTitle(btnDataArray[i].title, for: .normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
            btn.setTitleColor(UIColor.black, for: .normal)
            btn.setImage(UIImage(named: btnDataArray[i].icon!), for: .normal)
            btn.size = CGSize(width: 80, height: 110)
            self.addSubview(btn)
            
            //  计算列的索引
            let colIndex = i % 3
            //  计算行的索引
            let rowIndex = i / 3
            //  设置x坐标
            btn.x = CGFloat(colIndex) * buttonWidth + CGFloat(colIndex + 1) * buttonMargin
            //  设置y坐标
            btn.y = CGFloat(rowIndex) * buttonHeight + CGFloat(rowIndex) * buttonMargin + ScreenHeight
            btn.size = CGSize(width: buttonWidth, height: buttonHeight)

            buttonArray.append(btn)
        }
        
    }

    
    // 按钮组的弹簧动画
    fileprivate func popAnimation(isUp: Bool) {
    
        if isUp == false {
            //如果是向下运动  数组翻转
            buttonArray = buttonArray.reversed()
        
        }
        
        for (i, button) in buttonArray.enumerated() {
            //创建动画
            let pop = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            //设置弹簧效果 抖动幅度
            pop?.springBounciness = 10
            //设置抖动速度
            pop?.springSpeed = 10
            //动画开始时间
            pop?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            if isUp {
            
            pop?.toValue = CGPoint(x: button.centerX, y: button.centerY - 350)
            
            } else {
            
            pop?.toValue = CGPoint(x: button.centerX, y: button.centerY + 350)
            }
            //添加动画   如果在view上  需要添加到view上
            button.pop_add(pop, forKey: nil)
        }
    
    
    }
    //解析btn的plist文件
    fileprivate func getPlistData()->[YYLComposeModel] {
        let url = Bundle.main.url(forResource: "compose.plist", withExtension: nil)!
        let dicArray = NSArray(contentsOf: url)
        let tempArray = NSArray.yy_modelArray(with: YYLComposeModel.self, json: dicArray!) as! [YYLComposeModel]
        
        return tempArray
    }
    
    //每个按钮点击事件 和 放大缩小动画
    @objc private func composeBtnClick (btn: YYLComposeButton) {
    
        for button in buttonArray {
            
            if button == btn {//如果是这个按钮就放大

                UIView.animate(withDuration: 0.25, animations: {
                    
                   button.transform = CGAffineTransform(scaleX: 2, y: 2)
                }, completion: { (_) in
                    
                    UIView.animate(withDuration: 0.25, animations: {
                      button.transform = CGAffineTransform.identity
                    }, completion: { (_) in
                        //YYLComposeViewController
                        //根据类名获取控制器
                        let classType = NSClassFromString(self.btnDataArray[button.tag].className!) as! UIViewController.Type
                        
                        let vc = classType.init()
                        let nav = UINavigationController(rootViewController: vc)
                        
                        self.target?.present(nav, animated: true, completion: {
                            //动画完成后 把自己移除
                            self.removeFromSuperview()
                        })
                    })
                }) 

            } else {
                //不是这个按钮就缩小
                UIView.animate(withDuration: 0.25, animations: {
                    
                    button.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
                }, completion: { (_) in
                    
                    UIView.animate(withDuration: 0.25, animations: {
                        button.transform = CGAffineTransform.identity
                    }, completion: { (_) in

                    })
                })
            
            
            }
        }

    }

    //通过现在的view获取父控制器
    func show(target: UIViewController) {
    self.target = target
//    //把view加到Window上  所有的视图都在Window上  这次添加后  它下面的控制器弹出新控制后会看不见
//    UIApplication.shared.keyWindow?.addSubview(self)

        //把view添加到tabbar控制器上
        self.target?.view.addSubview(self)
    }
    
    
    
    
}
